package com.tarena.sentinel.demo02.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.sentinel.demo02.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    HelloService service;

    @GetMapping("/hello")
    public String sayHi(String name){

        Entry entry = null;
        String result = "";
        try {
            // entry入口对象,对sentinel资源的一次访问
            entry = SphU.entry("resource01");
            result = service.sayHi(name);
        } catch (BlockException e) {
            // 如果抛出异常,证明本次请求,超出了流量控制上限
            // 流控规则被触发,请求被拒绝(降级逻辑在此位置编写)
            return "你的请求被流量拦截了!";
        } finally {
            // 释放资源
            if(entry!=null){
                entry.exit();
            }
        }

        return result;
    }


}
